<template>
  <view class="payment-container">
    <!-- 顶部标题栏 -->
    <view class="page-header">
      <view class="header-title">订单支付</view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-card">
      <view class="order-header">
        <text class="order-title">{{ order.title }}</text>
        <text class="order-status">{{ getStatusText(order.status) }}</text>
      </view>
      
      <view class="order-details">
        <view class="detail-item">
          <text class="label">订单编号：</text>
          <text class="value">{{ order.id }}</text>
        </view>
        <view class="detail-item">
          <text class="label">服务地址：</text>
          <text class="value">{{ order.address }}</text>
        </view>
        <view class="detail-item">
          <text class="label">联系人：</text>
          <text class="value">{{ order.name }} {{ order.phone }}</text>
        </view>
        <view class="detail-item">
          <text class="label">下单时间：</text>
          <text class="value">{{ order.createTime }}</text>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="fee-breakdown">
      <view class="section-title">费用明细</view>
      <view class="fee-item">
        <text class="label">基础费用</text>
        <text class="value">¥{{ order.price?.toFixed(2) }}</text>
      </view>
      <view class="fee-item">
        <text class="label">服务费</text>
        <text class="value">¥{{ order.servicePay?.toFixed(2) }}</text>
      </view>
      <view class="fee-item total">
        <text class="label">总计</text>
        <text class="value total-amount">¥{{ totalPrice }}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-methods">
      <view class="section-title">支付方式</view>
      <view class="method-item" :class="{ active: selectedPaymentMethod === 'wechat' }" @click="selectPaymentMethod('wechat')">
        <image class="method-icon" src="/static/images/wechat-pay.png" mode="aspectFit"></image>
        <view class="method-info">
          <text class="method-name">微信支付</text>
          <text class="method-desc">推荐使用微信支付</text>
        </view>
        <text class="checkmark" v-if="selectedPaymentMethod === 'wechat'">✓</text>
      </view>
      <view class="method-item" :class="{ active: selectedPaymentMethod === 'alipay' }" @click="selectPaymentMethod('alipay')">
        <image class="method-icon" src="/static/images/alipay.png" mode="aspectFit"></image>
        <view class="method-info">
          <text class="method-name">支付宝支付</text>
          <text class="method-desc">推荐使用支付宝支付</text>
        </view>
        <text class="checkmark" v-if="selectedPaymentMethod === 'alipay'">✓</text>
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="pay-button-container">
      <button class="pay-button" @click="handlePayment">确认支付 ¥{{ totalPrice }}</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getWorkOrderDetailAPI } from '@/api/order.js'

// 订单数据
const order = ref({
  id: '',
  title: '',
  address: '',
  name: '',
  phone: '',
  createTime: '',
  price: 0,
  servicePay: 0,
  status: 0
})

// 选中的支付方式
const selectedPaymentMethod = ref('wechat')

// 计算总价
const totalPrice = computed(() => {
  const p = parseFloat(order.value.price) || 0;
  const s = parseFloat(order.value.servicePay) || 0;
  return (p + s).toFixed(2);
});

// 页面加载时获取订单详情
onLoad(async (options) => {
  console.log('支付页面加载，参数:', options);
  if (options && options.id) {
    console.log('开始获取订单详情，订单ID:', options.id);
    await fetchOrderDetail(options.id)
  } else {
    console.error('缺少订单ID参数');
    uni.showToast({
      title: '缺少订单ID参数',
      icon: 'none'
    });
  }
})

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    uni.showLoading({ title: '加载中...' })
    
    // 验证订单ID
    if (!orderId) {
      uni.showToast({
        title: '订单ID无效',
        icon: 'none'
      })
      return
    }
    
    console.log('开始调用获取订单详情API，订单ID:', orderId);
    const res = await getWorkOrderDetailAPI(orderId)
    console.log('获取订单详情API返回结果:', res);
    
    if (res && res.code === 0 && res.data) {
      console.log('订单详情数据:', res.data);
      // 验证订单状态是否可以支付
      if (res.data.status !== 2) {
        uni.showToast({
          title: '订单状态不正确，无法支付',
          icon: 'none'
        })
        console.error('订单状态不正确，当前状态:', res.data.status)
        return
      }
      
      // 验证订单是否已支付
      if (res.data.payStatus === 1) {
        uni.showToast({
          title: '订单已支付',
          icon: 'none'
        })
        console.error('订单已支付，支付状态:', res.data.payStatus)
        return
      }
      
      order.value = {
        ...res.data,
        // 确保数值字段正确，映射数据库字段
        price: res.data.pay !== undefined ? res.data.pay : (res.data.price || 0),
        servicePay: res.data.service_pay !== undefined ? res.data.service_pay : (res.data.servicePay || 0)
      }
      console.log('订单详情设置成功:', order.value);
    } else {
      console.error('获取订单详情失败，错误码:', res?.code, '错误信息:', res?.msg, '完整响应:', res)
      uni.showToast({
        title: res?.msg || '获取订单详情失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    uni.showToast({
      title: '网络请求失败，请检查网络连接',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '待分配',
    1: '处理中',
    2: '已完成',
    3: '已取消'
  }
  return map[status] || '未知状态'
}

// 选择支付方式
const selectPaymentMethod = (method) => {
  selectedPaymentMethod.value = method
}

// 处理支付
const handlePayment = () => {
  // 检查订单状态
  if (order.value.status !== 2) {
    uni.showToast({
      title: '订单状态不正确，无法支付',
      icon: 'none'
    })
    return
  }
  
  // 检查是否已支付
  if (order.value.payStatus === 1) {
    uni.showToast({
      title: '订单已支付',
      icon: 'none'
    })
    return
  }
  
  // 检查是否选择了支付方式
  if (!selectedPaymentMethod.value) {
    uni.showToast({
      title: '请选择支付方式',
      icon: 'none'
    })
    return
  }
  
  // 模拟支付处理
  uni.showLoading({ title: '支付处理中...' })
  
  // 模拟支付延迟
  setTimeout(() => {
    uni.hideLoading()
    
    // 模拟支付成功
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    })
    
    // 更新订单支付状态
    order.value.payStatus = 1
    
    // 调用后端接口更新订单支付状态
    updateOrderPayStatus()
  }, 2000)
}

// 更新订单支付状态
const updateOrderPayStatus = () => {
  // 调用后端接口更新订单支付状态
  uni.request({
    url: 'http://localhost:6009/order-client/api/workOrderInfo/update',
    method: 'POST',
    data: {
      id: order.value.id,
      payStatus: 1 // 已支付
    },
    success: (res) => {
      if (res.data && res.data.code === 0) {
        console.log('订单支付状态更新成功')
        // 支付状态更新成功后，跳转到订单列表页面
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/orders/orders'
          })
        }, 1000)
      } else {
        console.error('订单支付状态更新失败:', res.data?.msg || '未知错误')
        // 即使更新失败也跳转到订单页面
        uni.redirectTo({
          url: '/pages/orders/orders'
        })
      }
    },
    fail: (err) => {
      console.error('订单支付状态更新失败:', err)
      // 即使更新失败也跳转到订单页面
      uni.redirectTo({
        url: '/pages/orders/orders'
      })
    }
  })
}
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-size: 28rpx;
}

.page-header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.header-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

/* 订单信息卡片 */
.order-info-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.order-status {
  padding: 5rpx 15rpx;
  background-color: #e6ffed;
  color: #00b42a;
  border-radius: 40rpx;
  font-size: 24rpx;
}

.order-details .detail-item {
  display: flex;
  margin-bottom: 15rpx;
}

.order-details .detail-item:last-child {
  margin-bottom: 0;
}

.order-details .label {
  color: #999;
  width: 180rpx;
}

.order-details .value {
  flex: 1;
  color: #666;
}

/* 费用明细 */
.fee-breakdown {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
}

.fee-item.total {
  border-top: 1rpx solid #f0f0f0;
  margin-top: 10rpx;
  padding-top: 20rpx;
}

.fee-item .label {
  color: #666;
}

.fee-item .value {
  color: #333;
}

.fee-item .total-amount {
  color: #ff4d4f;
  font-size: 32rpx;
  font-weight: bold;
}

/* 支付方式 */
.payment-methods {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.method-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  cursor: pointer;
}

.method-item:last-child {
  margin-bottom: 0;
}

.method-item.active {
  border-color: #1677ff;
}

.method-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 28rpx;
  color: #333;
  display: block;
}

.method-desc {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.checkmark {
  color: #1677ff;
  font-weight: bold;
}

/* 支付按钮 */
.pay-button-container {
  padding: 40rpx 20rpx;
}

.pay-button {
  height: 88rpx;
  line-height: 88rpx;
  background-color: #07c160;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
}
</style>